package jnpf.engine.service.impl;


import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.dynamic.datasource.annotation.DSTransactional;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
import com.google.common.collect.ImmutableList;
import jnpf.base.UserInfo;
import jnpf.base.entity.DictionaryDataEntity;
import jnpf.base.service.DictionaryDataService;
import jnpf.base.service.SuperServiceImpl;
import jnpf.engine.assembly.GlobalExPropertyDTO;
import jnpf.engine.entity.*;
import jnpf.engine.enums.FlowRecordEnum;
import jnpf.engine.enums.FlowTaskStatusEnum;
import jnpf.engine.mapper.FlowTaskMapper;
import jnpf.engine.model.flowbefore.FlowBatchModel;
import jnpf.engine.model.flowengine.shuntjson.childnode.Properties;
import jnpf.engine.model.flowengine.shuntjson.nodejson.ChildNodeList;
import jnpf.engine.model.flowengine.shuntjson.nodejson.Custom;
import jnpf.engine.model.flowtask.FlowTaskListModel;
import jnpf.engine.model.flowtask.PaginationFlowTask;
import jnpf.engine.service.*;
import jnpf.engine.util.ActivitiUtils;
import jnpf.engine.util.FlowNature;
import jnpf.exception.WorkFlowException;
import jnpf.model.FlowWorkListVO;
import jnpf.model.FlowWorkModel;
import jnpf.permission.entity.UserEntity;
import jnpf.permission.model.user.WorkHandoverModel;
import jnpf.permission.service.UserService;
import jnpf.util.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.flowable.bpmn.model.Process;
import org.flowable.engine.HistoryService;
import org.flowable.engine.RepositoryService;
import org.flowable.engine.RuntimeService;
import org.flowable.engine.TaskService;
import org.flowable.engine.history.HistoricProcessInstance;
import org.flowable.engine.history.HistoricProcessInstanceQuery;
import org.flowable.engine.repository.ProcessDefinition;
import org.flowable.engine.runtime.ProcessInstance;
import org.flowable.task.api.Task;
import org.flowable.task.api.TaskQuery;
import org.flowable.task.api.history.HistoricTaskInstance;
import org.flowable.task.api.history.HistoricTaskInstanceQuery;
import org.flowable.variable.api.history.HistoricVariableInstance;
import org.flowable.variable.api.persistence.entity.VariableInstance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

import static jnpf.engine.custom.constants.BasicActivitiConstants.THIS_STEP_NAME;
import static jnpf.engine.custom.constants.GlobalProcessVariableConstants.*;
import static jnpf.engine.util.BpmnModelUtils.getAttributeValueByTaskDefinitionKey;
import static jnpf.engine.util.BpmnModelUtils.getBpmnModelMainProcess;

/**
 * 流程任务
 *
 * @author JNPF开发平台组
 * @version V3.1.0
 * @copyright 引迈信息技术有限公司
 * @date 2019年9月27日 上午9:18
 */
@Slf4j
@Service
public class FlowTaskServiceImpl extends SuperServiceImpl<FlowTaskMapper, FlowTaskEntity> implements FlowTaskService {

    @Autowired
    private UserProvider userProvider;
    @Autowired
    private ServiceAllUtil serviceUtil;
    @Autowired
    private FlowTemplateJsonService flowTemplateJsonService;
    @Autowired
    private FlowTaskNodeService flowTaskNodeService;
    @Autowired
    @Lazy
    private FlowTaskOperatorService flowTaskOperatorService;
    @Autowired
    private FlowOperatorUserService flowOperatorUserService;
    @Autowired
    private FlowTaskOperatorRecordService flowTaskOperatorRecordService;
    @Autowired
    private FlowTaskCirculateService flowTaskCirculateService;
    @Autowired
    private FlowTaskShareService flowTaskShareService;
    @Autowired
    private FlowCandidatesService flowCandidatesService;
    @Autowired
    private FlowCommentService flowCommentService;
    @Autowired
    private UserService userService;
    @Autowired
    private FlowEngineVisibleService flowEngineVisibleService;
    @Resource
    private HistoryService historyService;
    @Resource
    private RuntimeService runtimeService;
    @Resource
    private ActivitiUtils activitiUtils;
    @Resource
    private TaskService taskService;
    @Resource
    private RepositoryService repositoryService;
    @Resource
    private DictionaryDataService dictionaryDataService;

    @Override
    public List<FlowTaskEntity> getMonitorList(PaginationFlowTask paginationFlowTask) {
        HistoricProcessInstanceQuery historicProcessInstanceQuery = historyService.createHistoricProcessInstanceQuery();
        UserInfo userInfo = userProvider.get();
        historicProcessInstanceQuery.processInstanceTenantId(userInfo.getTenantId());
        QueryWrapper<FlowTaskEntity> queryWrapper = new QueryWrapper<>();
        String userId = userProvider.get().getUserId();
        //关键字（流程名称、流程编码）
        if(StringUtils.isNotBlank(paginationFlowTask.getKeyword())){
            historicProcessInstanceQuery.variableValueLikeIgnoreCase(jnpf.engine.custom.constants.GlobalProcessVariableConstants.BUSINESS_TITLE,"%"+paginationFlowTask.getKeyword()+"%");
        }
        //日期范围（近7天、近1月、近3月、自定义）
        Long startTime = paginationFlowTask.getStartTime() != null ? paginationFlowTask.getStartTime() : null;
        Long endTime = paginationFlowTask.getEndTime() != null ? paginationFlowTask.getEndTime() : null;
        if(startTime!=null){
            Date startTimeDate = new Date(startTime);
            historicProcessInstanceQuery.startedAfter(startTimeDate);
        }
        if(endTime!=null){
            Date endTimeDate = new Date(endTime);
            historicProcessInstanceQuery.startedBefore(endTimeDate);
        }
        //所属流程
        String templateId = paginationFlowTask.getTemplateId() != null ? paginationFlowTask.getTemplateId() : null;
        if (ObjectUtil.isNotEmpty(templateId)) {
            historicProcessInstanceQuery.variableValueEquals(FLOW_ENGINE_ID,paginationFlowTask.getTemplateId());
        }
        //所属名称
        if(StringUtils.isNotBlank(paginationFlowTask.getFlowId())){
            historicProcessInstanceQuery.variableValueEquals(FLOW_TEMPLATE_JSON_ID,paginationFlowTask.getFlowId());
        }
        //流程状态
        String pageOpType = paginationFlowTask.getPageOpType();
        if(StringUtils.isNotBlank(pageOpType)){
            historicProcessInstanceQuery.variableValueEquals(PROCESS_STATUS, FlowTaskStatusEnum.Adopt.getCode());
        }
        else{
            Integer status = paginationFlowTask.getStatus() != null ? paginationFlowTask.getStatus() : null;
            if (ObjectUtil.isNotEmpty(status)) {
                historicProcessInstanceQuery.variableValueEquals(PROCESS_STATUS,status);
            }
        }
        List<UserEntity> adminList = userService.getAdminList();
        String creatorUserId = adminList.stream().anyMatch(e -> e.getId().equals(userId))? null:StringUtils.defaultIfBlank(paginationFlowTask.getCreatorUserId(),userId);
        if(StringUtils.isNotBlank(creatorUserId)){
            historicProcessInstanceQuery.variableValueEquals(APPLY_USER_ID,creatorUserId);
        }
        //紧急程度
        Integer flowUrgent = paginationFlowTask.getFlowUrgent() != null ? paginationFlowTask.getFlowUrgent() : null;
        if (ObjectUtil.isNotEmpty(flowUrgent)) {
            historicProcessInstanceQuery.variableValueEquals(FLOW_URGENT,flowUrgent);
        }
        //所属分类
        if(StringUtils.isNotBlank(paginationFlowTask.getFlowCategory())){
            DictionaryDataEntity infoByEnCode = dictionaryDataService.getInfoByEnCode(paginationFlowTask.getFlowCategory());
            if(Objects.nonNull(infoByEnCode)){
                historicProcessInstanceQuery.variableValueEquals(PROCESS_CATEGORY,infoByEnCode.getId());
            }
        }
        //排序
        if ("asc".equals(paginationFlowTask.getSort().toLowerCase())) {
            historicProcessInstanceQuery.orderByProcessInstanceStartTime().asc();
        } else {
            historicProcessInstanceQuery.orderByProcessInstanceStartTime().desc();
        }

        Integer currentPage = Integer.valueOf(paginationFlowTask.getCurrentPage() + "");
        Integer pageSize = Integer.valueOf(paginationFlowTask.getPageSize() + "");
        long count = historicProcessInstanceQuery.count();

        List<HistoricProcessInstance> historicProcessInstances = historicProcessInstanceQuery
                .listPage((currentPage - 1) * pageSize, pageSize);
        List<FlowTaskEntity> flowTaskEntityList = new ArrayList<>();
        if (CollUtil.isNotEmpty(historicProcessInstances)) {
            /**

             */
            Set<String> processInstanceIds = new HashSet<>();
            for (HistoricProcessInstance historicProcessInstance : historicProcessInstances) {
                processInstanceIds.add(historicProcessInstance.getId());
            }
            List<HistoricVariableInstance> list = historyService.createHistoricVariableInstanceQuery().executionIds(processInstanceIds).list();
            Map<String,Map<String,Object>> variablesInstances= new HashMap<>();
            for (HistoricVariableInstance historicVariableInstance : list) {
                Map<String,Object> map = variablesInstances.get(historicVariableInstance.getProcessInstanceId());
                if(CollUtil.isEmpty(map)){
                    map=new HashMap<>();
                    map.put(historicVariableInstance.getVariableName(),historicVariableInstance.getValue());
                    variablesInstances.put(historicVariableInstance.getProcessInstanceId(),map);
                }
                else{
                    map.put(historicVariableInstance.getVariableName(),historicVariableInstance.getValue());
                    variablesInstances.put(historicVariableInstance.getProcessInstanceId(),map);
                }
            }
            for (HistoricProcessInstance historicProcessInstance : historicProcessInstances) {
                String processDefinitionId = historicProcessInstance.getProcessDefinitionId();
                Process process = getBpmnModelMainProcess(processDefinitionId);
                String property = getAttributeValueByTaskDefinitionKey(process, "", "global");
                jnpf.engine.assembly.GlobalExPropertyDTO exPropertyDTO = JSONObject.parseObject(property, new TypeReference<jnpf.engine.assembly.GlobalExPropertyDTO>() {});
                Map<String, Object> map = variablesInstances.get(historicProcessInstance.getId());
                FlowTaskEntity flowTaskEntity = new FlowTaskEntity();
                flowTaskEntity.setId(historicProcessInstance.getId());
                flowTaskEntity.setProcessId(historicProcessInstance.getId());
                flowTaskEntity.setEnCode(MapUtil.getStr(map,BILL_CODE));//单据规则
                flowTaskEntity.setFullName(MapUtil.getStr(map,BUSINESS_TITLE));
                flowTaskEntity.setFlowUrgent(MapUtil.getInt(map,FLOW_URGENT));
                flowTaskEntity.setFlowId(exPropertyDTO.getFlowTemplateJsonId());
                flowTaskEntity.setTemplateId(exPropertyDTO.getFlowTemplateId());
                flowTaskEntity.setFlowCode(process.getId());
                flowTaskEntity.setFlowName(process.getName());
                flowTaskEntity.setFlowType(exPropertyDTO.getFlowType());
                flowTaskEntity.setFlowCategory(MapUtil.getStr(map,PROCESS_CATEGORY));
                flowTaskEntity.setFlowVersion(historicProcessInstance.getProcessDefinitionVersion()+"");
                flowTaskEntity.setStatus(MapUtil.getInt(map,PROCESS_STATUS));
                if(historicProcessInstance.getEndTime()==null){
                    flowTaskEntity.setThisStep(activitiUtils.getCurrentNodeNameStr(historicProcessInstance.getId()));
                    flowTaskEntity.setCompletion(50);
                }
                else{
                    flowTaskEntity.setCompletion(100);
                    flowTaskEntity.setThisStep(THIS_STEP_NAME);
                }
                flowTaskEntity.setDescription(process.getDocumentation());
                flowTaskEntity.setParentId(historicProcessInstance.getSuperProcessInstanceId());
                flowTaskEntity.setCreatorTime(historicProcessInstance.getStartTime());
                flowTaskEntity.setStartTime(historicProcessInstance.getStartTime());
                flowTaskEntity.setEndTime(historicProcessInstance.getEndTime());
                flowTaskEntity.setCreatorUserId(MapUtil.getStr(map,APPLY_USER_ID));
                flowTaskEntityList.add(flowTaskEntity);
            }
        }
        return paginationFlowTask.setData(flowTaskEntityList,count);
    }

    @Override
    public List<FlowTaskEntity> getLaunchList(PaginationFlowTask paginationFlowTask) {
        HistoricProcessInstanceQuery historicProcessInstanceQuery = historyService.createHistoricProcessInstanceQuery();
        UserInfo userInfo = userProvider.get();
        String userId = userInfo.getUserId();
        if (StringUtil.isNotEmpty(paginationFlowTask.getUserId())) {
            userId = paginationFlowTask.getUserId();
        }
        log.info("getLaunchList userId : {}", userId);
        historicProcessInstanceQuery.processInstanceTenantId(userInfo.getTenantId());
        if (paginationFlowTask.getDelegateType()) {
            historicProcessInstanceQuery.variableValueEquals(DELEGATE_USER_ID, userId);
        } else {
            //        historicProcessInstanceQuery.startedBy(userInfo.getUserId()); //调用活动无法所以不能使用
            historicProcessInstanceQuery.variableValueEquals(APPLY_USER_ID, userId);
        }
        //关键字（流程名称、流程编码）
        if(StringUtils.isNotBlank(paginationFlowTask.getKeyword())){
            historicProcessInstanceQuery.variableValueLikeIgnoreCase(jnpf.engine.custom.constants.GlobalProcessVariableConstants.BUSINESS_TITLE,"%"+paginationFlowTask.getKeyword()+"%");
        }
        //日期范围（近7天、近1月、近3月、自定义）
        Long startTime = paginationFlowTask.getStartTime();
        Long endTime = paginationFlowTask.getEndTime();
        if(startTime!=null){
            historicProcessInstanceQuery.startedAfter(new Date(paginationFlowTask.getStartTime()));
        }
        if(endTime!=null){
            historicProcessInstanceQuery.startedBefore(new Date(paginationFlowTask.getEndTime()));
        }
        //所属流程
        String templateId = paginationFlowTask.getTemplateId() != null ? paginationFlowTask.getTemplateId() : null;
        if (ObjectUtil.isNotEmpty(templateId)) {
            historicProcessInstanceQuery.variableValueEquals(FLOW_ENGINE_ID,paginationFlowTask.getTemplateId());
        }
        //所属名称
        if(StringUtils.isNotBlank(paginationFlowTask.getFlowId())){
            historicProcessInstanceQuery.variableValueEquals(FLOW_TEMPLATE_JSON_ID,paginationFlowTask.getFlowId());
        }
        //流程状态
        Integer status = paginationFlowTask.getStatus() != null ? paginationFlowTask.getStatus() : null;
        if (ObjectUtil.isNotEmpty(status)) {
            historicProcessInstanceQuery.variableValueEquals(PROCESS_STATUS,status);
        }
        //紧急程度
        Integer flowUrgent = paginationFlowTask.getFlowUrgent() != null ? paginationFlowTask.getFlowUrgent() : null;
        if (ObjectUtil.isNotEmpty(flowUrgent)) {
            historicProcessInstanceQuery.variableValueEquals(FLOW_URGENT,flowUrgent);
        }
        //所属分类
        if (StringUtils.isNotBlank(paginationFlowTask.getFlowCategory())) {
            DictionaryDataEntity infoByEnCode = dictionaryDataService.getInfoByEnCode(paginationFlowTask.getFlowCategory());
            if (Objects.nonNull(infoByEnCode)) {
                historicProcessInstanceQuery.variableValueEquals(PROCESS_CATEGORY, infoByEnCode.getId());
            }
        }
        //排序
        if ("asc".equals(paginationFlowTask.getSort().toLowerCase())) {
            historicProcessInstanceQuery.orderByProcessInstanceStartTime().asc();
        } else {
            historicProcessInstanceQuery.orderByProcessInstanceStartTime().desc();
        }

        Integer currentPage = Integer.valueOf(paginationFlowTask.getCurrentPage() + "");
        Integer pageSize = Integer.valueOf(paginationFlowTask.getPageSize() + "");
        long count = historicProcessInstanceQuery.count();

        List<HistoricProcessInstance> historicProcessInstances = historicProcessInstanceQuery
                .listPage((currentPage - 1) * pageSize, pageSize);
        List<FlowTaskEntity> flowTaskEntityList = new ArrayList<>();
        if (CollUtil.isNotEmpty(historicProcessInstances)) {
            /**

             */
            Set<String> processInstanceIds = new HashSet<>();
            for (HistoricProcessInstance historicProcessInstance : historicProcessInstances) {
                processInstanceIds.add(historicProcessInstance.getId());
            }
            List<HistoricVariableInstance> list = historyService.createHistoricVariableInstanceQuery().executionIds(processInstanceIds).list();
            Map<String,Map<String,Object>> variablesInstances= new HashMap<>();
            for (HistoricVariableInstance historicVariableInstance : list) {
                Map<String,Object> map = variablesInstances.get(historicVariableInstance.getProcessInstanceId());
                if(CollUtil.isEmpty(map)){
                    map=new HashMap<>();
                    map.put(historicVariableInstance.getVariableName(),historicVariableInstance.getValue());
                    variablesInstances.put(historicVariableInstance.getProcessInstanceId(),map);
                }
                else{
                    map.put(historicVariableInstance.getVariableName(),historicVariableInstance.getValue());
                    variablesInstances.put(historicVariableInstance.getProcessInstanceId(),map);
                }
            }
            for (HistoricProcessInstance historicProcessInstance : historicProcessInstances) {
                String processDefinitionId = historicProcessInstance.getProcessDefinitionId();
                Process process = getBpmnModelMainProcess(processDefinitionId);
                String property = getAttributeValueByTaskDefinitionKey(process, "", "global");
                jnpf.engine.assembly.GlobalExPropertyDTO exPropertyDTO = JSONObject.parseObject(property, new TypeReference<GlobalExPropertyDTO>() {});
                Map<String, Object> map = variablesInstances.get(historicProcessInstance.getId());
                FlowTaskEntity flowTaskEntity = new FlowTaskEntity();
                flowTaskEntity.setProcessInstanceId(historicProcessInstance.getId());
                flowTaskEntity.setBusinessKey(historicProcessInstance.getBusinessKey());
                flowTaskEntity.setId(historicProcessInstance.getBusinessKey());
                flowTaskEntity.setProcessId(historicProcessInstance.getBusinessKey());
                flowTaskEntity.setEnCode(MapUtil.getStr(map,BILL_CODE));//单据规则
                flowTaskEntity.setFullName(MapUtil.getStr(map,BUSINESS_TITLE));
                flowTaskEntity.setFlowUrgent(MapUtil.getInt(map,FLOW_URGENT));
                flowTaskEntity.setFlowId(exPropertyDTO.getFlowTemplateJsonId());
                flowTaskEntity.setTemplateId(exPropertyDTO.getFlowTemplateId());
                flowTaskEntity.setFlowCode(process.getId());
                flowTaskEntity.setFlowName(process.getName());
                flowTaskEntity.setFlowType(exPropertyDTO.getFlowType());
                flowTaskEntity.setFlowCategory(MapUtil.getStr(map,PROCESS_CATEGORY));

                flowTaskEntity.setStatus(MapUtil.getInt(map,PROCESS_STATUS));
                if(historicProcessInstance.getEndTime()==null){
                    flowTaskEntity.setThisStep(activitiUtils.getCurrentNodeNameStr(historicProcessInstance.getId()));
                    flowTaskEntity.setCompletion(50);
                }
                else{
                    flowTaskEntity.setCompletion(100);
                    flowTaskEntity.setThisStep(THIS_STEP_NAME);
                }
                flowTaskEntity.setDescription(process.getDocumentation());
                flowTaskEntity.setParentId(historicProcessInstance.getSuperProcessInstanceId());
                flowTaskEntity.setCreatorTime(historicProcessInstance.getStartTime());
                flowTaskEntity.setStartTime(historicProcessInstance.getStartTime());
                flowTaskEntity.setEndTime(historicProcessInstance.getEndTime());
                flowTaskEntity.setCreatorUserId(historicProcessInstance.getStartUserId());
                flowTaskEntityList.add(flowTaskEntity);
            }
        }
        return paginationFlowTask.setData(flowTaskEntityList,count);
    }

    @Override
    public List<FlowTaskListModel> getWaitList(PaginationFlowTask paginationFlowTask) {
        UserInfo userInfo = userProvider.get();
        String userId =userInfo.getUserId();
        if (StringUtil.isNotEmpty(paginationFlowTask.getUserId())) {
            userId = paginationFlowTask.getUserId();
        }
        log.info("getWaitList userId : {}", userId);
        TaskQuery taskQuery = taskService.createTaskQuery().taskAssignee(userId)
                .processVariableValueNotEquals(PROCESS_STATUS,FlowTaskStatusEnum.Draft.getCode());
        taskQuery.taskTenantId(userInfo.getTenantId());
        /*.processVariableValueNotEquals(PROCESS_STATUS,FlowTaskStatusEnum.Revoke.getCode());*/
        //关键字（流程名称、流程编码）
        String keyWord = paginationFlowTask.getKeyword() ;
        if (ObjectUtil.isNotEmpty(keyWord)) {
            taskQuery.processVariableValueLikeIgnoreCase(BUSINESS_TITLE,"%"+keyWord+"%");
        }
        //日期范围（近7天、近1月、近3月、自定义）
        Long startTime = paginationFlowTask.getStartTime() ;
        Long endTime = paginationFlowTask.getEndTime() ;
        if (ObjectUtil.isNotEmpty(startTime) && ObjectUtil.isNotEmpty(endTime)) {
            Date startTimes = new Date(startTime);
            Date endTimes = new Date(endTime);
            taskQuery.taskCreatedBefore(endTimes);
            taskQuery.taskCreatedAfter(startTimes);
        }


        //流程模板
        String templateId = paginationFlowTask.getTemplateId() ;
        //所属流程
        if (ObjectUtil.isNotEmpty(templateId)) {
            taskQuery.processVariableValueEquals(FLOW_ENGINE_ID,templateId);
        }
        //所属名称
        if(StringUtils.isNotBlank(paginationFlowTask.getFlowId())){
            taskQuery.processVariableValueEquals(FLOW_TEMPLATE_JSON_ID,paginationFlowTask.getFlowId());
        }
        //
        //所属分类
        String flowCategory = paginationFlowTask.getFlowCategory();
        if (StringUtils.isNotBlank(flowCategory)) {
            DictionaryDataEntity infoByEnCode = dictionaryDataService.getInfoByEnCode(paginationFlowTask.getFlowCategory());
            if (Objects.nonNull(infoByEnCode)) {
                taskQuery.processVariableValueEquals(PROCESS_CATEGORY, infoByEnCode.getId());
            }

        }

        //发起人员
        String creatorUserId = paginationFlowTask.getCreatorUserId() ;
        if(StringUtils.isNotBlank(creatorUserId)){
            taskQuery.processVariableValueEquals(APPLY_USER_ID,creatorUserId);
        }
        //紧急程度
        Integer flowUrgent = paginationFlowTask.getFlowUrgent() ;
        if(flowUrgent!=null){
            taskQuery.processVariableValueEquals(FLOW_URGENT,flowUrgent);
        }

        //判断是否是批量审批
        Integer isBatch = paginationFlowTask.getIsBatch();
        if(isBatch!=null){
            taskQuery.processVariableValueEquals(BATCH_FLAG,isBatch);
        }

        long count = taskQuery.active().count();
        Integer currentPage = Integer.valueOf(paginationFlowTask.getCurrentPage() + "");
        Integer pageSize = Integer.valueOf(paginationFlowTask.getPageSize() + "");
        List<Task> tasks = taskQuery.active().orderByTaskCreateTime().desc()
                .listPage((currentPage - 1) * pageSize, pageSize);
        List<FlowTaskListModel> result = new LinkedList<>();

        if(CollUtil.isNotEmpty(tasks)){
            Set<String> ids = new HashSet<>();
            for (Task task : tasks) {
                ids.add(task.getProcessInstanceId());
            }
            List<VariableInstance> variablesList = runtimeService.getVariableInstancesByExecutionIds(ids);
            Map<String,Map<String,Object>> variablesMap = new HashMap<>();
            for (VariableInstance variableInstance : variablesList) {
                Map<String, Object> map = variablesMap.get(variableInstance.getProcessInstanceId());
                if(map==null){
                    map = new HashMap<>();
                    map.put(variableInstance.getName(),variableInstance.getValue());
                    variablesMap.put(variableInstance.getProcessInstanceId(),map);
                }
                else{
                    map.put(variableInstance.getName(),variableInstance.getValue());
                    variablesMap.put(variableInstance.getProcessInstanceId(),map);
                }
            }
            for (Task task : tasks) {
                ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery().processDefinitionId(task.getProcessDefinitionId()).singleResult();
                Map<String, Object> map = variablesMap.get(task.getProcessInstanceId());
                FlowTaskListModel flowTaskListModel = new FlowTaskListModel();

                if(isBatch!=null){
                    if(1==isBatch){
                        String property = getAttributeValueByTaskDefinitionKey(getBpmnModelMainProcess(task.getProcessDefinitionId()), task.getTaskDefinitionKey(), "userTask");
                        ChildNodeList childNodeList  = new ChildNodeList();
                        childNodeList.setTaskId(task.getProcessInstanceId());
                        childNodeList.setTaskNodeId(task.getId());
                        childNodeList.setProperties(JSONObject.parseObject(property,new TypeReference<Properties>(){}));
                        Custom custom = new Custom();
                        custom.setType("approver");
                        custom.setNodeId(task.getTaskDefinitionKey());
                        flowTaskListModel.setApproversProperties(JsonUtil.getObjectToString(childNodeList));
                    }
                }
                flowTaskListModel.setId(task.getId());
                flowTaskListModel.setProcessId(task.getId());
                flowTaskListModel.setEnCode(MapUtil.getStr(map,BILL_CODE));
                flowTaskListModel.setFullName(MapUtil.getStr(map,BUSINESS_TITLE));
                flowTaskListModel.setFlowUrgent(MapUtil.getInt(map,FLOW_URGENT));
                flowTaskListModel.setFlowId(MapUtil.getStr(map,FLOW_TEMPLATE_JSON_ID));
                flowTaskListModel.setFlowCode(processDefinition.getKey());
                flowTaskListModel.setFlowName(processDefinition.getName());
                flowTaskListModel.setFlowCategory(MapUtil.getStr(map,PROCESS_CATEGORY));
                flowTaskListModel.setFlowVersion(processDefinition.getVersion()+"");
//            flowTaskListModel.setFlowType();
                flowTaskListModel.setStartTime(MapUtil.getDate(map,CURRENT_CREATE_TIME));
                flowTaskListModel.setThisStep(activitiUtils.getCurrentNodeNameStr(task.getProcessInstanceId()));
                flowTaskListModel.setThisStepId(task.getId());
                flowTaskListModel.setStatus(MapUtil.getInt(map,PROCESS_STATUS));
//            flowTaskListModel.setCompletion();
                flowTaskListModel.setCreatorUserId(MapUtil.getStr(map,APPLY_USER_ID));
                flowTaskListModel.setCreatorTime(task.getCreateTime());
                flowTaskListModel.setHandleId(task.getAssignee());
                flowTaskListModel.setNodeName(task.getName());
                flowTaskListModel.setDescription(task.getDescription());
                flowTaskListModel.setTemplateId(MapUtil.getStr(map,FLOW_ENGINE_ID));
                flowTaskListModel.setProcessInstanceId(task.getProcessInstanceId());
                flowTaskListModel.setWTaskId(task.getId());
                result.add(flowTaskListModel);
            }
        }


        return paginationFlowTask.setData(PageUtil.getListPage((int) paginationFlowTask.getCurrentPage(), (int) paginationFlowTask.getPageSize(), result), count);
    }

    @Override
    public List<FlowTaskListModel> getCirculateList(PaginationFlowTask paginationFlowTask) {
        UserInfo userInfo = userProvider.get();
        String userId = userInfo.getUserId();
//        Map<String, Object> map = new HashMap<>();
//        List<String> objectId = new ArrayList<>();
//        objectId.add(userId);
//        List<UserRelationEntity> list = serviceUtil.getListByUserIdAll(objectId);
//        objectId.addAll(list.stream().map(UserRelationEntity::getObjectId).collect(Collectors.toList()));
        //
        if(StringUtils.isNotBlank(paginationFlowTask.getPageOpType())){
            LambdaQueryWrapper<FlowTaskShareEntity> lambdaQueryWrapper= new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(FlowTaskShareEntity::getObjectId,userId);
            if(StringUtils.isNotBlank(userInfo.getTenantId())){
                lambdaQueryWrapper.eq(FlowTaskShareEntity::getTenantId,userInfo.getTenantId());
            }
            //传阅人员
            //关键字（流程名称、流程编码）
            String keyWord = paginationFlowTask.getKeyword();
            if (ObjectUtil.isNotEmpty(keyWord)) {
                lambdaQueryWrapper.like(FlowTaskShareEntity::getFullName,keyWord);
            }
            //日期范围（近7天、近1月、近3月、自定义）
            Long startTime = paginationFlowTask.getStartTime() != null ? paginationFlowTask.getStartTime() : null;
            Long endTime = paginationFlowTask.getEndTime() != null ? paginationFlowTask.getEndTime() : null;
            if (ObjectUtil.isNotEmpty(startTime) && ObjectUtil.isNotEmpty(endTime)) {
                Date startTimes = new Date(startTime);
                Date endTimes = new Date(endTime);
                lambdaQueryWrapper.ge(FlowTaskShareEntity::getCreatorTime,startTimes);
                lambdaQueryWrapper.le(FlowTaskShareEntity::getCreatorTime,endTimes);
            }
            //流程模板
            String templateId = paginationFlowTask.getTemplateId() ;
            if(StringUtils.isNotBlank(templateId)){
                lambdaQueryWrapper.eq(FlowTaskShareEntity::getTemplateId,templateId);
            }
            //所属流程
            String flowId = paginationFlowTask.getFlowId();
            if(StringUtils.isNotBlank(flowId)){
                lambdaQueryWrapper.eq(FlowTaskShareEntity::getFlowId,flowId);
            }
            //所属分类
            String flowCategory = paginationFlowTask.getFlowCategory();
            if (StringUtils.isNotBlank(flowCategory)) {
                DictionaryDataEntity infoByEnCode = dictionaryDataService.getInfoByEnCode(paginationFlowTask.getFlowCategory());
                if (Objects.nonNull(infoByEnCode)) {
                    lambdaQueryWrapper.eq(FlowTaskShareEntity::getFlowCategory, infoByEnCode.getId());
                }
            }

            //发起人员
            String creatorUserId = paginationFlowTask.getCreatorUserId() ;
            if(StringUtils.isNotBlank(creatorUserId)){
                lambdaQueryWrapper.eq(FlowTaskShareEntity::getApplyUserId,creatorUserId);
            }
            //紧急程度
            Integer flowUrgent = paginationFlowTask.getFlowUrgent() ;
            if(flowUrgent!=null){
                lambdaQueryWrapper.eq(FlowTaskShareEntity::getFlowUrgent,flowUrgent);
            }
            lambdaQueryWrapper.orderByDesc(FlowTaskShareEntity::getCreatorTime);
            long count = flowTaskShareService.count(lambdaQueryWrapper);
            List<FlowTaskListModel> flowTaskListModelList = new ArrayList<>();
            List<FlowTaskShareEntity> list = flowTaskShareService.list(lambdaQueryWrapper);
            if(CollUtil.isNotEmpty(list)){
                Set<String> ids = new HashSet<>();
                for (FlowTaskShareEntity flowTaskCirculateEntity : list) {
                    ids.add(flowTaskCirculateEntity.getTaskId());
                }
                List<HistoricProcessInstance> historicProcessInstances = historyService.createHistoricProcessInstanceQuery().processInstanceIds(ids).includeProcessVariables().list();
                Map<String,HistoricProcessInstance> processInstanceMap= new HashMap<>();
                for (HistoricProcessInstance historicProcessInstance : historicProcessInstances) {
                    processInstanceMap.put(historicProcessInstance.getId(),historicProcessInstance);
                }
                for (FlowTaskShareEntity flowTaskCirculateEntity : list) {

                    HistoricProcessInstance historicProcessInstance = processInstanceMap.get(flowTaskCirculateEntity.getTaskId());
                    if (ObjectUtil.isNull(historicProcessInstance)) {
                        continue;
                    }
                    Map<String, Object> processVariables = historicProcessInstance.getProcessVariables();
                    Process bpmnModelMainProcess = getBpmnModelMainProcess(historicProcessInstance.getProcessDefinitionId());
                    FlowTaskListModel flowTaskListModel = new FlowTaskListModel();
                    flowTaskListModel.setId(flowTaskCirculateEntity.getTaskId());
                    flowTaskListModel.setProcessId(flowTaskCirculateEntity.getTaskId());
                    flowTaskListModel.setEnCode(flowTaskCirculateEntity.getEnCode());
                    flowTaskListModel.setFullName(flowTaskCirculateEntity.getFullName());
                    flowTaskListModel.setFlowUrgent(MapUtil.getInt(processVariables,FLOW_URGENT));
                    flowTaskListModel.setFlowId(flowTaskCirculateEntity.getFlowId());
                    flowTaskListModel.setFlowCode(historicProcessInstance.getProcessDefinitionKey());
                    flowTaskListModel.setFlowName(historicProcessInstance.getProcessDefinitionName());
                    flowTaskListModel.setFlowCategory(flowTaskCirculateEntity.getFlowCategory());
                    flowTaskListModel.setStartTime(historicProcessInstance.getStartTime());
//                String currentNodeName = activitiUtils.getCurrentNodeName(bpmnModelMainProcess, runtimeService.getActiveActivityIds(historicProcessInstance.getId()));
                    flowTaskListModel.setThisStep(activitiUtils.getCurrentNodeNameStr(historicProcessInstance.getId()));
                    flowTaskListModel.setThisStepId(flowTaskCirculateEntity.getTaskNodeId());
                    flowTaskListModel.setStatus(MapUtil.getInt(processVariables,PROCESS_STATUS));
                    flowTaskListModel.setUserName(flowTaskCirculateEntity.getApplyUserId());
                    flowTaskListModel.setCreatorUserId(flowTaskCirculateEntity.getApplyUserIdReal());
                    flowTaskListModel.setCreatorTime(flowTaskCirculateEntity.getCreatorTime());
                    flowTaskListModel.setLastModifyUserId(flowTaskCirculateEntity.getApplyUserId());
                    flowTaskListModel.setLastModifyTime(flowTaskCirculateEntity.getCreatorTime());
                    flowTaskListModel.setStartTime(historicProcessInstance.getStartTime());
                    flowTaskListModelList.add(flowTaskListModel);
                }
            }
            return paginationFlowTask.setData(PageUtil.getListPage((int) paginationFlowTask.getCurrentPage(), (int) paginationFlowTask.getPageSize(), flowTaskListModelList), count);
        }
        else{
            LambdaQueryWrapper<FlowTaskCirculateEntity> lambdaQueryWrapper= new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(FlowTaskCirculateEntity::getObjectId,userId);
            if(StringUtils.isNotBlank(userInfo.getTenantId())){
                lambdaQueryWrapper.eq(FlowTaskCirculateEntity::getTenantId,userInfo.getTenantId());
            }
            //传阅人员
            //关键字（流程名称、流程编码）
            String keyWord = paginationFlowTask.getKeyword();
            if (ObjectUtil.isNotEmpty(keyWord)) {
                lambdaQueryWrapper.like(FlowTaskCirculateEntity::getFullName,keyWord);
            }
            //日期范围（近7天、近1月、近3月、自定义）
            Long startTime = paginationFlowTask.getStartTime() != null ? paginationFlowTask.getStartTime() : null;
            Long endTime = paginationFlowTask.getEndTime() != null ? paginationFlowTask.getEndTime() : null;
            if (ObjectUtil.isNotEmpty(startTime) && ObjectUtil.isNotEmpty(endTime)) {
                Date startTimes = new Date(startTime);
                Date endTimes = new Date(endTime);
                lambdaQueryWrapper.ge(FlowTaskCirculateEntity::getCreatorTime,startTimes);
                lambdaQueryWrapper.le(FlowTaskCirculateEntity::getCreatorTime,endTimes);
            }
            //流程模板
            String templateId = paginationFlowTask.getTemplateId() ;
            if(StringUtils.isNotBlank(templateId)){
                lambdaQueryWrapper.eq(FlowTaskCirculateEntity::getTemplateId,templateId);
            }
            //所属流程
            String flowId = paginationFlowTask.getFlowId();
            if(StringUtils.isNotBlank(flowId)){
                lambdaQueryWrapper.eq(FlowTaskCirculateEntity::getFlowId,flowId);
            }
            //所属分类
            String flowCategory = paginationFlowTask.getFlowCategory() ;
            if(StringUtils.isNotBlank(flowCategory)){
                lambdaQueryWrapper.eq(FlowTaskCirculateEntity::getFlowCategory,flowCategory);
            }

            //发起人员
            String creatorUserId = paginationFlowTask.getCreatorUserId() ;
            if(StringUtils.isNotBlank(creatorUserId)){
                lambdaQueryWrapper.eq(FlowTaskCirculateEntity::getApplyUserId,creatorUserId);
            }
            //紧急程度
            Integer flowUrgent = paginationFlowTask.getFlowUrgent() ;
            if(flowUrgent!=null){
                lambdaQueryWrapper.eq(FlowTaskCirculateEntity::getFlowUrgent,flowUrgent);
            }
            lambdaQueryWrapper.orderByDesc(FlowTaskCirculateEntity::getCreatorTime);
            long count = flowTaskCirculateService.count(lambdaQueryWrapper);
            List<FlowTaskListModel> flowTaskListModelList = new ArrayList<>();
            List<FlowTaskCirculateEntity> list = flowTaskCirculateService.list(lambdaQueryWrapper);
            if(CollUtil.isNotEmpty(list)){
                Set<String> ids = new HashSet<>();
                for (FlowTaskCirculateEntity flowTaskCirculateEntity : list) {
                    ids.add(flowTaskCirculateEntity.getTaskId());
                }
                List<HistoricProcessInstance> historicProcessInstances = historyService.createHistoricProcessInstanceQuery().processInstanceIds(ids).includeProcessVariables().list();
                Map<String,HistoricProcessInstance> processInstanceMap= new HashMap<>();
                for (HistoricProcessInstance historicProcessInstance : historicProcessInstances) {
                    processInstanceMap.put(historicProcessInstance.getId(),historicProcessInstance);
                }
                for (FlowTaskCirculateEntity flowTaskCirculateEntity : list) {

                    HistoricProcessInstance historicProcessInstance = processInstanceMap.get(flowTaskCirculateEntity.getTaskId());
                    Map<String, Object> processVariables = historicProcessInstance.getProcessVariables();
                    Process bpmnModelMainProcess = getBpmnModelMainProcess(historicProcessInstance.getProcessDefinitionId());
                    FlowTaskListModel flowTaskListModel = new FlowTaskListModel();
                    flowTaskListModel.setId(flowTaskCirculateEntity.getTaskId());
                    flowTaskListModel.setProcessId(flowTaskCirculateEntity.getTaskId());
                    flowTaskListModel.setEnCode(flowTaskCirculateEntity.getEnCode());
                    flowTaskListModel.setFullName(flowTaskCirculateEntity.getFullName());
                    flowTaskListModel.setFlowUrgent(MapUtil.getInt(processVariables,FLOW_URGENT));
                    flowTaskListModel.setFlowId(flowTaskCirculateEntity.getFlowId());
                    flowTaskListModel.setFlowCode(historicProcessInstance.getProcessDefinitionKey());
                    flowTaskListModel.setFlowName(historicProcessInstance.getProcessDefinitionName());
                    flowTaskListModel.setFlowCategory(flowTaskCirculateEntity.getFlowCategory());
                    flowTaskListModel.setStartTime(historicProcessInstance.getStartTime());
//                String currentNodeName = activitiUtils.getCurrentNodeName(bpmnModelMainProcess, runtimeService.getActiveActivityIds(historicProcessInstance.getId()));
                    flowTaskListModel.setThisStep(activitiUtils.getCurrentNodeNameStr(historicProcessInstance.getId()));
                    flowTaskListModel.setThisStepId(flowTaskCirculateEntity.getTaskNodeId());
                    flowTaskListModel.setStatus(MapUtil.getInt(processVariables,PROCESS_STATUS));
                    flowTaskListModel.setUserName(flowTaskCirculateEntity.getApplyUserId());
                    flowTaskListModel.setCreatorUserId(flowTaskCirculateEntity.getApplyUserIdReal());
                    flowTaskListModel.setCreatorTime(flowTaskCirculateEntity.getCreatorTime());
                    flowTaskListModel.setLastModifyUserId(flowTaskCirculateEntity.getApplyUserId());
                    flowTaskListModel.setLastModifyTime(flowTaskCirculateEntity.getCreatorTime());
                    flowTaskListModel.setStartTime(historicProcessInstance.getStartTime());
                    flowTaskListModelList.add(flowTaskListModel);
                }
            }
            return paginationFlowTask.setData(PageUtil.getListPage((int) paginationFlowTask.getCurrentPage(), (int) paginationFlowTask.getPageSize(), flowTaskListModelList), count);
        }
    }

    @Override
    public List<FlowTaskListModel> getTrialList(PaginationFlowTask paginationFlowTask) {
        HistoricTaskInstanceQuery taskQuery = historyService.createHistoricTaskInstanceQuery();
        taskQuery.taskWithoutDeleteReason();
        UserInfo userInfo = userProvider.get();
        String userId = userInfo.getUserId();
        if (StringUtil.isNotEmpty(paginationFlowTask.getUserId())) {
            userId = paginationFlowTask.getUserId();
        }
        log.info("getTrialList userId : {}", userId);
        taskQuery.taskAssignee(userId);
        taskQuery.taskTenantId(userInfo.getTenantId());
        //关键字（流程名称、流程编码）
        String keyWord = paginationFlowTask.getKeyword();
        if (ObjectUtil.isNotEmpty(keyWord)) {
            taskQuery.processVariableValueLikeIgnoreCase(BUSINESS_TITLE,"%"+keyWord+"%");
        }
        //日期范围（近7天、近1月、近3月、自定义）
        Long startTime = paginationFlowTask.getStartTime() ;
        Long endTime = paginationFlowTask.getEndTime() ;
        if (ObjectUtil.isNotEmpty(startTime) && ObjectUtil.isNotEmpty(endTime)) {
            Date startTimes= new Date(startTime);
            Date endTimes = new Date(endTime);
            taskQuery.taskCreatedBefore(endTimes);
            taskQuery.taskCreatedAfter(startTimes);
        }
        //流程模板
        String templateId = paginationFlowTask.getTemplateId() ;
        if (ObjectUtil.isNotEmpty(templateId)) {
            taskQuery.processVariableValueEquals(FLOW_ENGINE_ID,templateId);
        }
        //所属流程
        String flowId = paginationFlowTask.getFlowId() ;
        if (StringUtil.isNotEmpty(flowId)) {
            taskQuery.processVariableValueEquals(FLOW_TEMPLATE_JSON_ID,paginationFlowTask.getFlowId());
        }
        //所属分类
        String flowCategory = paginationFlowTask.getFlowCategory();
        if (StringUtils.isNotBlank(flowCategory)) {
            DictionaryDataEntity infoByEnCode = dictionaryDataService.getInfoByEnCode(paginationFlowTask.getFlowCategory());
            if (Objects.nonNull(infoByEnCode)) {
                taskQuery.processVariableValueEquals(PROCESS_CATEGORY, infoByEnCode.getId());
            }
        }
        //发起人员
        String creatorUserId = paginationFlowTask.getCreatorUserId() ;
        if(StringUtils.isNotBlank(creatorUserId)){
            taskQuery.processVariableValueEquals(APPLY_USER_ID,creatorUserId);
        }
        //紧急程度
        Integer flowUrgent = paginationFlowTask.getFlowUrgent() ;
        if(flowUrgent!=null){
            taskQuery.processVariableValueEquals(FLOW_URGENT,flowUrgent);
        }
        long count = taskQuery.finished().count();
        Integer currentPage = Integer.valueOf(paginationFlowTask.getCurrentPage() + "");
        Integer pageSize = Integer.valueOf(paginationFlowTask.getPageSize() + "");



        List<HistoricTaskInstance> tasks = taskQuery.finished()/*.includeTaskLocalVariables()*/.orderByTaskCreateTime().desc()
                .listPage((currentPage - 1) * pageSize, pageSize);

        Set<String> executionIds =  new HashSet<>();
        for (HistoricTaskInstance task : tasks) {
            executionIds.add(task.getProcessInstanceId());
        }
        List<HistoricVariableInstance> list= new ArrayList<>();
        if(CollUtil.isNotEmpty(executionIds)){
            list=historyService.createHistoricVariableInstanceQuery().executionIds(executionIds).list();
        }
        Map<String,Map<String,Object>> variablesInstances= new HashMap<>();
        for (HistoricVariableInstance historicVariableInstance : list) {
            Map<String,Object> map = variablesInstances.get(historicVariableInstance.getProcessInstanceId());
            if(CollUtil.isEmpty(map)){
                map=new HashMap<>();
                map.put(historicVariableInstance.getVariableName(),historicVariableInstance.getValue());
                variablesInstances.put(historicVariableInstance.getProcessInstanceId(),map);
            }
            else{
                map.put(historicVariableInstance.getVariableName(),historicVariableInstance.getValue());
                variablesInstances.put(historicVariableInstance.getProcessInstanceId(),map);
            }
        }

        List<FlowTaskListModel> result = new ArrayList<>();
        for (HistoricTaskInstance task : tasks) {
            ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery().processDefinitionId(task.getProcessDefinitionId()).singleResult();
            Map<String, Object> map = variablesInstances.get(task.getProcessInstanceId());
//            String property = getAttributeValueByTaskDefinitionKey(getBpmnModelMainProcess(task.getProcessDefinitionId()), task.getTaskDefinitionKey(), "userTask");
            FlowTaskListModel flowTaskListModel = new FlowTaskListModel();
            flowTaskListModel.setId(task.getId());
            flowTaskListModel.setProcessId(task.getId());
            flowTaskListModel.setEnCode(MapUtil.getStr(map,BILL_CODE));
            flowTaskListModel.setFullName(MapUtil.getStr(map,BUSINESS_TITLE));
            flowTaskListModel.setFlowUrgent(MapUtil.getInt(map,FLOW_URGENT));
            flowTaskListModel.setFlowId(MapUtil.getStr(map,FLOW_TEMPLATE_JSON_ID));
            flowTaskListModel.setFlowCode(processDefinition.getKey());
            flowTaskListModel.setFlowName(processDefinition.getName());
            flowTaskListModel.setFlowCategory(MapUtil.getStr(map,PROCESS_CATEGORY));
            flowTaskListModel.setFlowVersion(processDefinition.getVersion()+"");
//            flowTaskListModel.setFlowType();
            flowTaskListModel.setStartTime(MapUtil.getDate(map,CURRENT_CREATE_TIME));
            flowTaskListModel.setThisStep(task.getName());
            flowTaskListModel.setThisStepId(task.getId());
            flowTaskListModel.setStatus(MapUtil.getInt(map,PROCESS_STATUS));
            if(task.getPriority()==50){
                flowTaskListModel.setTaskStatus(FlowRecordEnum.audit.getCode());
            }
            else{
                flowTaskListModel.setTaskStatus(FlowRecordEnum.reject.getCode());
            }
            flowTaskListModel.setCreatorUserId(MapUtil.getStr(map,APPLY_USER_ID));
            flowTaskListModel.setCreatorTime(task.getEndTime());
            flowTaskListModel.setHandleId(task.getAssignee());
            flowTaskListModel.setNodeName(task.getName());
            flowTaskListModel.setDescription(task.getDescription());
            flowTaskListModel.setTemplateId(MapUtil.getStr(map,FLOW_ENGINE_ID));
            result.add(flowTaskListModel);
        }
//        for (String key : dataAll.keySet()) {
//            List<FlowTaskListModel> flowTaskListModels = dataAll.get(key).stream().sorted(Comparator.comparing(FlowTaskListModel::getCreatorTime).reversed()).collect(Collectors.toList());
//            if (flowTaskListModels.size() > 0) {
//                FlowTaskListModel entity = flowTaskListModels.get(0);
//                boolean isuser = entity.getHandleId().equals(entity.getDelegateUser());
//                entity.setDelegateUser(!isuser ? entity.getCreatorUserId() : null);
//                result.add(flowTaskListModels.get(0));
//            }
//        }
//        result = result.stream().sorted(Comparator.comparing(FlowTaskListModel::getCreatorTime).reversed()).collect(Collectors.toList());

        return paginationFlowTask.setData(PageUtil.getListPage((int) paginationFlowTask.getCurrentPage(), (int) paginationFlowTask.getPageSize(), result), count);
    }

    @Override
    public FlowTaskEntity getInfo(String id, SFunction<FlowTaskEntity, ?>... columns) throws WorkFlowException {
        QueryWrapper<FlowTaskEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(FlowTaskEntity::getId, id);
        queryWrapper.lambda().select(columns);
        FlowTaskEntity entity = this.getOne(queryWrapper);
        if (entity == null) {
            throw new WorkFlowException("");
        }
        return entity;
    }

    @Override
    public void update(FlowTaskEntity entity) {
        this.updateById(entity);
    }

    @Override
    public void create(FlowTaskEntity entity) {
        this.save(entity);
    }

    @Override
    public void createOrUpdate(FlowTaskEntity entity) {
        this.saveOrUpdate(entity);
    }

    @Override
    public FlowTaskEntity getInfoSubmit(String id, SFunction<FlowTaskEntity, ?>... columns) {
        HistoricProcessInstance historicProcessInstance = historyService.createHistoricProcessInstanceQuery().processInstanceBusinessKey(id).singleResult();
        HistoricVariableInstance historicVariableInstance = historyService.createHistoricVariableInstanceQuery().processInstanceId(historicProcessInstance.getId()).variableName(PROCESS_STATUS).singleResult();
        FlowTaskEntity flowTaskEntity = new FlowTaskEntity();
        flowTaskEntity.setId(id);
        flowTaskEntity.setStatus((Integer) historicVariableInstance.getValue());
        flowTaskEntity.setParentId(historicProcessInstance.getSuperProcessInstanceId());
        return flowTaskEntity;
//        List<FlowTaskEntity> list = getInfosSubmit(new String[]{id}, columns);
//        if (list.isEmpty()) {
//            return null;
//        }
//        return list.get(0);
    }

    @Override
    public List<FlowTaskEntity> getInfosSubmit(String[] ids, SFunction<FlowTaskEntity, ?>... columns) {
        List<FlowTaskEntity> resultList = Collections.emptyList();
        if (ids == null || ids.length == 0) {
            return resultList;
        }
        LambdaQueryWrapper<FlowTaskEntity> queryWrapper = new LambdaQueryWrapper<>();
        if (ids.length == 1) {
            queryWrapper.select(columns).and(
                    t -> t.eq(FlowTaskEntity::getId, ids[0])
            );
            resultList = this.list(queryWrapper);
            if (resultList.isEmpty()) {
                queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.select(columns).and(
                        t -> t.eq(FlowTaskEntity::getProcessId, ids[0])
                );
                resultList = this.list(queryWrapper);
            }
        } else {
            queryWrapper.select(FlowTaskEntity::getId).and(t -> {
                t.in(FlowTaskEntity::getId, ids).or().in(FlowTaskEntity::getProcessId, ids);
            });
            List<String> resultIds = this.listObjs(queryWrapper, t -> t.toString());
            if (!resultIds.isEmpty()) {
                queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.select(columns).in(FlowTaskEntity::getId, resultIds);
                resultList = this.list(queryWrapper);
            }
        }
        return resultList;
    }

    @Override
    public void delete(FlowTaskEntity entity) throws WorkFlowException {
        if (FlowTaskStatusEnum.Suspend.getCode().equals(entity.getStatus())) {
            throw new WorkFlowException("流程处于挂起状态，不可操作");
        }
        if (!FlowNature.ParentId.equals(entity.getParentId()) && StringUtil.isNotEmpty(entity.getParentId())) {
            throw new WorkFlowException(entity.getFullName() + "不能删除");
        }
  /*      if (!checkStatus(entity.getStatus())) {
            throw new WorkFlowException(MsgCode.WF116.get());
//        } else {*/
            List<String> idList = ImmutableList.of(entity.getId());
            this.deleteAllByBusinessKey(idList, true, true);
//        }
    }

    @Override
    public void delete(String id) throws WorkFlowException {
        List<String> idList = ImmutableList.of(id);
        this.deleteAll(idList, true, true);
    }

    @Override
    public void deleteChildAll(List<String> idAll) {
        this.deleteAll(idAll, true, true);
    }

    @Override
    @DSTransactional
    public void delete(String[] ids) throws WorkFlowException {
        UserInfo userInfo = userProvider.get();
        if (ids.length > 0) {



            List<String> idList = Arrays.asList(ids);
            HashSet<String> set = CollUtil.newHashSet(idList);
            List<HistoricProcessInstance> list = historyService.createHistoricProcessInstanceQuery().processInstanceIds(set).includeProcessVariables().list();
            for (HistoricProcessInstance historicProcessInstance : list) {
                Process bpmnModelMainProcess = getBpmnModelMainProcess(historicProcessInstance.getProcessDefinitionId());
                String globalEx = getAttributeValueByTaskDefinitionKey(bpmnModelMainProcess, "", "global");
                GlobalExPropertyDTO globalExPropertyDTO = JSONObject.parseObject(globalEx, new TypeReference<GlobalExPropertyDTO>() {
                });
//                if(globalExPropertyDTO.getFlowType()==1){
//                    throw new WorkFlowException(historicProcessInstance.getName() + "不允许删除");
//                }
                if(historicProcessInstance.getEndTime()==null){
                    ProcessInstance processInstance = runtimeService.createProcessInstanceQuery().processInstanceId(historicProcessInstance.getId()).singleResult();
                    if(processInstance.isSuspended()){
                        throw new WorkFlowException(historicProcessInstance.getName() + "已被挂起不能删除");
                    }
                }
                if(StringUtils.isNotBlank(historicProcessInstance.getSuperProcessInstanceId())){
                    throw new WorkFlowException(historicProcessInstance.getName() +"不允许删除");
                }
                if (!userInfo.getIsAdministrator()) {
                    Map<String, Object> processVariables = historicProcessInstance.getProcessVariables();
                    String applyUserId = MapUtil.getStr(processVariables, APPLY_USER_ID);
                    String businessTitle = MapUtil.getStr(processVariables, BUSINESS_TITLE);
                    List<String> organizeUserList = serviceUtil.getOrganizeUserList("delete");
                    if(!organizeUserList.contains(applyUserId)){
                        throw new WorkFlowException(businessTitle + "没有删除权限");
                    }
                }
            }
            this.deleteAll(idList, true, true);
        }
    }

    @Override
    public List<FlowTaskEntity> getOrderStaList(List<String> id, SFunction<FlowTaskEntity, ?>... columns) {
        List<FlowTaskEntity> list = new ArrayList<>();
        if (id.size() > 0) {
            QueryWrapper<FlowTaskEntity> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().in(FlowTaskEntity::getId, id);
            list = this.list(queryWrapper);
        }
        return list;
    }

    @Override
    public List<FlowTaskEntity> getChildList(String id, SFunction<FlowTaskEntity, ?>... columns) {
        return getChildList(ImmutableList.of(id), columns);
    }

    @Override
    public List<FlowTaskEntity> getChildList(List<String> id, SFunction<FlowTaskEntity, ?>... columns) {
        QueryWrapper<FlowTaskEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().select(columns).in(FlowTaskEntity::getParentId, id);
        return this.list(queryWrapper);
    }

    @Override
    public List<FlowTaskEntity> getTemplateIdList(String tempId) {
        QueryWrapper<FlowTaskEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(FlowTaskEntity::getTemplateId, tempId);
        queryWrapper.lambda().select(FlowTaskEntity::getId, FlowTaskEntity::getFlowId);
        return this.list(queryWrapper);
    }

    @Override
    public List<FlowTaskEntity> getFlowList(String flowId) {
        QueryWrapper<FlowTaskEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(FlowTaskEntity::getFlowId, flowId);
        queryWrapper.lambda().select(FlowTaskEntity::getId);
        return list(queryWrapper);
    }

    @Override
    public List<FlowBatchModel> batchFlowSelector() {
        List<FlowTaskOperatorEntity> operatorList = flowTaskOperatorService.getBatchList();
        List<String> taskIdList = operatorList.stream().map(FlowTaskOperatorEntity::getTaskId).collect(Collectors.toList());
        List<FlowTaskEntity> taskList = getOrderStaList(taskIdList);
        Map<String, List<FlowTaskEntity>> flowList = taskList.stream().filter(t -> ObjectUtil.isNotEmpty(t.getIsBatch()) && t.getIsBatch() == 1).collect(Collectors.groupingBy(FlowTaskEntity::getTemplateId));
        List<FlowBatchModel> batchFlowList = new ArrayList<>();
        for (String key : flowList.keySet()) {
            List<FlowTaskEntity> flowTaskList = flowList.get(key);
            List<String> flowTask = flowTaskList.stream().map(FlowTaskEntity::getId).collect(Collectors.toList());
            List<FlowTemplateJsonEntity> templateJsonList = flowTemplateJsonService.getTemplateJsonList(flowTaskList.stream().map(FlowTaskEntity::getFlowId).collect(Collectors.toList()));
            if (flowTaskList.size() > 0) {
                String flowName = flowTaskList.stream().map(FlowTaskEntity::getFlowName).distinct().collect(Collectors.joining(","));
                String flowId = templateJsonList.stream().map(FlowTemplateJsonEntity::getTemplateId).distinct().collect(Collectors.joining(","));
                Long count = operatorList.stream().filter(t -> flowTask.contains(t.getTaskId())).count();
                FlowBatchModel batchModel = new FlowBatchModel();
                batchModel.setNum(count);
                batchModel.setId(flowId);
                batchModel.setFullName(flowName + "(" + count + ")");
                batchFlowList.add(batchModel);
            }
        }
        batchFlowList = batchFlowList.stream().sorted(Comparator.comparing(FlowBatchModel::getNum).reversed()).collect(Collectors.toList());
        return batchFlowList;
    }

    @Override
    public List<String> getChildAllList(String id) {
        List<String> idAll = new ArrayList<>();
        List<String> idList = ImmutableList.of(id);
        this.deleTaskAll(idList, idAll);
        return idAll;
    }

    @Override
    public void deleTaskAll(List<String> idList, List<String> idAll) {
        idAll.addAll(idList);
        for (String id : idList) {
            List<FlowTaskEntity> taskAll = this.getChildList(id, FlowTaskEntity::getId);
            List<String> list = taskAll.stream().map(FlowTaskEntity::getId).collect(Collectors.toList());
            this.deleTaskAll(list, idAll);
        }
    }

    @Override
    public void getChildList(String id, boolean suspend, List<String> list) {
        List<FlowTaskEntity> taskAll = this.getChildList(id, FlowTaskEntity::getId, FlowTaskEntity::getIsAsync);
        if (suspend) {
            taskAll = taskAll.stream().filter(t -> FlowNature.ChildSync.equals(t.getIsAsync())).collect(Collectors.toList());
        }
        for (FlowTaskEntity entity : taskAll) {
            list.add(entity.getId());
            this.getChildList(entity.getId(), suspend, list);
        }
    }

    @Override
    public FlowWorkListVO flowWork(String fromId) {
        FlowWorkListVO vo = new FlowWorkListVO();
        //代办
        QueryWrapper<FlowTaskOperatorEntity> operatorWrapper = new QueryWrapper<>();
        operatorWrapper.lambda().eq(FlowTaskOperatorEntity::getHandleId, fromId);
        List<FlowTaskOperatorEntity> list = flowTaskOperatorService.list(operatorWrapper);
        List<String> taskIdList = list.stream().map(FlowTaskOperatorEntity::getTaskId).collect(Collectors.toList());
//        List<FlowTaskEntity> taskList = getOrderStaList(taskIdList);
//        List<FlowTemplateEntity> waitTemplateList = flowTemplateService.getTemplateList(list.stream().map(FlowTaskOperatorEntity::).collect(Collectors.toList()));
        List<FlowWorkModel> waitList = new ArrayList<>();
        for (FlowTaskOperatorEntity entity : list) {
            FlowWorkModel workModel = JsonUtil.getJsonToBean(entity, FlowWorkModel.class);
//            FlowTaskEntity taskEntity = taskList.stream().filter(t -> t.getId().equals(entity.getTaskId())).findFirst().orElse(null);
//            if (taskEntity != null) {
                workModel.setFullName(entity.getNodeName());
//                FlowTemplateEntity templateEntity = waitTemplateList.stream().filter(t -> t.getId().equals(taskEntity.getTemplateId())).findFirst().orElse(null);
//                if (templateEntity != null) {
//                    workModel.setIcon(templateEntity.getIcon());
//                }
//            }
            waitList.add(workModel);
        }
        vo.setWait(waitList);

        //流程
//        QueryWrapper<FlowTemplateJsonEntity> queryWrapper = new QueryWrapper<>();
//        List<FlowTemplateJsonEntity> templateJsonList = flowTemplateJsonService.list(queryWrapper).stream().filter(t -> t.getFlowTemplateJson().contains(fromId)).collect(Collectors.toList());
//        List<String> templateIdList = templateJsonList.stream().map(FlowTemplateJsonEntity::getTemplateId).collect(Collectors.toList());
//        List<FlowTemplateEntity> templateList = flowTemplateService.getTemplateList(templateIdList);
//        List<FlowWorkModel> flowList = new ArrayList<>();
//        for (FlowTemplateJsonEntity entity : templateJsonList) {
//            FlowWorkModel workModel = JsonUtil.getJsonToBean(entity, FlowWorkModel.class);
//            FlowTemplateEntity templateEntity = templateList.stream().filter(t -> t.getId().equals(entity.getTemplateId())).findFirst().orElse(null);
//            if (templateEntity != null) {
//                workModel.setFullName(templateEntity.getFullName() + "_" + entity.getFullName() + "(V" + entity.getVersion() + ")");
//                workModel.setIcon(templateEntity.getIcon());
//            }
//            flowList.add(workModel);
//        }
//        vo.setFlow(flowList);
        return vo;
    }

    @Override
    @Transactional
    public boolean flowWork(WorkHandoverModel workHandoverModel) {
        String fromId = workHandoverModel.getFromId();
        String toId = workHandoverModel.getToId();
        List<String> waitList = workHandoverModel.getWaitList();
        //待办事宜
        if (waitList.size() > 0) {
            LambdaQueryWrapper<FlowTaskOperatorEntity> operator = new LambdaQueryWrapper<>();
            operator.in(FlowTaskOperatorEntity::getId, waitList);
            operator.eq(FlowTaskOperatorEntity::getHandleId, fromId);
//            operator.lambda().set(FlowTaskOperatorEntity::getHandleId, toId);
//            flowTaskOperatorService.update(operator);
            List<FlowTaskOperatorEntity> list = flowTaskOperatorService.list(operator);
            if(CollUtil.isNotEmpty(list)){
                for (FlowTaskOperatorEntity flowTaskOperatorEntity : list) {
                    String taskNodeId = flowTaskOperatorEntity.getTaskNodeId();
                    try{
                        taskService.setAssignee(taskNodeId,fromId);
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                }
                for (FlowTaskOperatorEntity flowTaskOperatorEntity : list) {
                    flowTaskOperatorEntity.setHandleId(toId);
                }
                flowTaskOperatorService.updateBatchById(list);
            }


            UpdateWrapper<FlowOperatorUserEntity> userOperator = new UpdateWrapper<>();
            userOperator.lambda().in(FlowOperatorUserEntity::getId, waitList);
            userOperator.lambda().eq(FlowOperatorUserEntity::getHandleId, fromId);
            userOperator.lambda().set(FlowOperatorUserEntity::getHandleId, toId);
            flowOperatorUserService.update(userOperator);
            UpdateWrapper<FlowCandidatesEntity> candidates = new UpdateWrapper<>();
            candidates.lambda().in(FlowCandidatesEntity::getId, waitList);
            candidates.lambda().eq(FlowCandidatesEntity::getHandleId, fromId);
            candidates.lambda().set(FlowCandidatesEntity::getHandleId, toId);
            flowCandidatesService.update(candidates);
        }
        //负责流程
        List<String> flowList = workHandoverModel.getFlowList();
        if (flowList.size() > 0) {
            UserEntity toUser = serviceUtil.getUserInfo(toId);
            String toUserName = toUser != null ? toUser.getRealName() + "/" + toUser.getAccount() : "";
            UserEntity fromUser = serviceUtil.getUserInfo(fromId);
            String fromUserName = fromUser != null ? fromUser.getRealName() + "/" + fromUser.getAccount() : "";
            //json
            List<FlowTemplateJsonEntity> templateJsonList = flowTemplateJsonService.getTemplateJsonList(flowList);
            for (FlowTemplateJsonEntity entity : templateJsonList) {
                String json = entity.getFlowTemplateJson().replaceAll(fromId, toId).replaceAll(fromUserName, toUserName);
                entity.setFlowTemplateJson(json);
                flowTemplateJsonService.update(entity.getId(), entity);
            }
            //任务
            QueryWrapper<FlowTaskEntity> taskQueryWrapper = new QueryWrapper<>();
            taskQueryWrapper.lambda().in(FlowTaskEntity::getFlowId, flowList);
            List<FlowTaskEntity> list = this.list(taskQueryWrapper);
            for (FlowTaskEntity entity : list) {
                update(entity);
                QueryWrapper<FlowTaskNodeEntity> nodeQueryWrapper = new QueryWrapper<>();
                nodeQueryWrapper.lambda().eq(FlowTaskNodeEntity::getTaskId, entity.getId());
                List<FlowTaskNodeEntity> nodeList = flowTaskNodeService.list(nodeQueryWrapper);
                for (FlowTaskNodeEntity taskNodeEntity : nodeList) {
                    taskNodeEntity.setNodePropertyJson(taskNodeEntity.getNodePropertyJson().replaceAll(fromId, toId).replaceAll(fromUserName, toUserName));
                    flowTaskNodeService.update(taskNodeEntity);
                }
            }
            //流程可见
            List<String> templateIdList = templateJsonList.stream().map(FlowTemplateJsonEntity::getTemplateId).collect(Collectors.toList());
            if (templateIdList.size() > 0) {
                UpdateWrapper<FlowEngineVisibleEntity> visibleWrapper = new UpdateWrapper<>();
                visibleWrapper.lambda().eq(FlowEngineVisibleEntity::getOperatorId, fromId);
                visibleWrapper.lambda().in(FlowEngineVisibleEntity::getFlowId, templateIdList);
                visibleWrapper.lambda().set(FlowEngineVisibleEntity::getOperatorId, toId);
                flowEngineVisibleService.update(visibleWrapper);
            }
        }
        return true;
    }

    /**
     * 验证有效状态
     *
     * @param status 状态编码
     * @return
     */
    private boolean checkStatus(int status) {
        List<Integer> statusList = ImmutableList.of(/*FlowTaskStatusEnum.Draft.getCode(),*/
                FlowTaskStatusEnum.Reject.getCode(), FlowTaskStatusEnum.Revoke.getCode());
        if (statusList.contains(status)) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 递归删除所有子节点
     *
     * @param idList
     * @param isRecord
     * @param isCirculate
     */
    private void deleteAll(List<String> idList, boolean isRecord, boolean isCirculate) {
        List<String> idAll = new ArrayList<>();
        idAll.addAll(idList);
//        this.deleTaskAll(idList, idAll);
        if (idAll.size() > 0) {
            for (String s : idAll) {
                long count = runtimeService.createProcessInstanceQuery().processInstanceId(s).count();
                if(count>0){
                    runtimeService.deleteProcessInstance(s,"删除流程");
                }
            }
            historyService.bulkDeleteHistoricProcessInstances(idAll);
//            QueryWrapper<FlowTaskEntity> task = new QueryWrapper<>();
//            task.lambda().in(FlowTaskEntity::getId, idAll);
//            this.remove(task);
//            QueryWrapper<FlowCandidatesEntity> candidates = new QueryWrapper<>();
//            candidates.lambda().in(FlowCandidatesEntity::getTaskId, idAll);
//            flowCandidatesService.remove(candidates);
            QueryWrapper<FlowCommentEntity> comment = new QueryWrapper<>();
            comment.lambda().in(FlowCommentEntity::getTaskId, idAll);
            flowCommentService.remove(comment);
//            QueryWrapper<FlowAuthorizeEntity> authorize = new QueryWrapper<>();
//            authorize.lambda().in(FlowAuthorizeEntity::getTaskId, idAll);
//            flowAuthorizeService.remove(authorize);
//            QueryWrapper<FlowUserEntity> user = new QueryWrapper<>();
//            user.lambda().in(FlowUserEntity::getTaskId, idAll);
//            flowUserService.remove(user);
//            QueryWrapper<FlowTaskNodeEntity> node = new QueryWrapper<>();
//            node.lambda().in(FlowTaskNodeEntity::getTaskId, idAll);
//            flowTaskNodeService.remove(node);
            QueryWrapper<FlowTaskOperatorEntity> operator = new QueryWrapper<>();
            operator.lambda().in(FlowTaskOperatorEntity::getTaskId, idAll);
            flowTaskOperatorService.remove(operator);
//            QueryWrapper<FlowOperatorUserEntity> operatorUser = new QueryWrapper<>();
//            operatorUser.lambda().in(FlowOperatorUserEntity::getTaskId, idAll);
//            flowOperatorUserService.remove(operatorUser);
//            QueryWrapper<FlowRejectDataEntity> rejectData = new QueryWrapper<>();
//            rejectData.lambda().in(FlowRejectDataEntity::getId, idAll);
//            flowRejectDataService.remove(rejectData);
            QueryWrapper<FlowTaskOperatorRecordEntity> record = new QueryWrapper<>();
            record.lambda().in(FlowTaskOperatorRecordEntity::getTaskId, idAll);
            flowTaskOperatorRecordService.remove(record);
            QueryWrapper<FlowTaskCirculateEntity> circulate = new QueryWrapper<>();
            circulate.lambda().in(FlowTaskCirculateEntity::getTaskId, idAll);
            flowTaskCirculateService.remove(circulate);
        }
    }
    private void deleteAllByBusinessKey(List<String> idList, boolean isRecord, boolean isCirculate) {
        List<String> idAll = new ArrayList<>();
        idAll.addAll(idList);
//        this.deleTaskAll(idList, idAll);
        List<String> processInstanceIdsAll = new ArrayList<>();
        if (idAll.size() > 0) {
            for (String s : idAll) {
                HistoricProcessInstance historicProcessInstance = historyService.createHistoricProcessInstanceQuery().processInstanceBusinessKey(s).singleResult();
                if(historicProcessInstance!=null ){
                    if(historicProcessInstance.getEndTime()==null){
                        runtimeService.deleteProcessInstance(historicProcessInstance.getId(),"删除流程");
                    }
                    processInstanceIdsAll.add(historicProcessInstance.getId());
                }

            }
            historyService.bulkDeleteHistoricProcessInstances(processInstanceIdsAll);
//            QueryWrapper<FlowTaskEntity> task = new QueryWrapper<>();
//            task.lambda().in(FlowTaskEntity::getId, idAll);
//            this.remove(task);
//            QueryWrapper<FlowCandidatesEntity> candidates = new QueryWrapper<>();
//            candidates.lambda().in(FlowCandidatesEntity::getTaskId, idAll);
//            flowCandidatesService.remove(candidates);
            QueryWrapper<FlowCommentEntity> comment = new QueryWrapper<>();
            comment.lambda().in(FlowCommentEntity::getTaskId, processInstanceIdsAll);
            flowCommentService.remove(comment);
//            QueryWrapper<FlowAuthorizeEntity> authorize = new QueryWrapper<>();
//            authorize.lambda().in(FlowAuthorizeEntity::getTaskId, idAll);
//            flowAuthorizeService.remove(authorize);
//            QueryWrapper<FlowUserEntity> user = new QueryWrapper<>();
//            user.lambda().in(FlowUserEntity::getTaskId, idAll);
//            flowUserService.remove(user);
//            QueryWrapper<FlowTaskNodeEntity> node = new QueryWrapper<>();
//            node.lambda().in(FlowTaskNodeEntity::getTaskId, idAll);
//            flowTaskNodeService.remove(node);
            QueryWrapper<FlowTaskOperatorEntity> operator = new QueryWrapper<>();
            operator.lambda().in(FlowTaskOperatorEntity::getTaskId, processInstanceIdsAll);
            flowTaskOperatorService.remove(operator);
//            QueryWrapper<FlowOperatorUserEntity> operatorUser = new QueryWrapper<>();
//            operatorUser.lambda().in(FlowOperatorUserEntity::getTaskId, idAll);
//            flowOperatorUserService.remove(operatorUser);
//            QueryWrapper<FlowRejectDataEntity> rejectData = new QueryWrapper<>();
//            rejectData.lambda().in(FlowRejectDataEntity::getId, idAll);
//            flowRejectDataService.remove(rejectData);
            QueryWrapper<FlowTaskOperatorRecordEntity> record = new QueryWrapper<>();
            record.lambda().in(FlowTaskOperatorRecordEntity::getTaskId, processInstanceIdsAll);
            flowTaskOperatorRecordService.remove(record);
            QueryWrapper<FlowTaskCirculateEntity> circulate = new QueryWrapper<>();
            circulate.lambda().in(FlowTaskCirculateEntity::getTaskId, processInstanceIdsAll);
            flowTaskCirculateService.remove(circulate);
        }
    }

}
